<?php

namespace App\Http\Controllers\Admin\Setting\Permission;

use App\Http\Controllers\Admin\Controller;
use App\Repositories\Permission\AdminRepository;
use App\Repositories\Permission\RoleRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Inertia\Response;

class AccountController extends Controller
{
    protected array $validateMessages = [
        'name.*' => '请输入账号名称',
        'phone.unique' => '该手机号已存在',
        'phone.*' => '请输入正确的手机号',
        'email.unique' => '该邮箱已存在',
        'email.*' => '请输入正确的邮箱',
        'password.*' => '请输入正确的密码',
        'confirm_password.*' => '请输入正确的确认密码',
        'avatar.*' => '请上传头像',
        'status.*' => '请输入正确的状态',
    ];

    public function __construct(Request $request, AdminRepository $repository)
    {
        $this->request = $request;
        $this->repository = $repository;
    }

    public function index(RoleRepository $roleRepository): Response
    {
        $params = $this->request->all();
        $list = $this->repository->paginate($params);
        return $this->inertia('setting/permission/account/index',[
            'data' => $list->items(),
            'pagination' => [
                'total' => $list->total(),
                'page' => $list->currentPage(),
                'pageSize' => $list->perPage(),
                'showTotal' => true,
            ],
            'options' => $roleRepository->getSelect(),
        ]);
    }

    public function show($id): array
    {
        $row = $this->repository->getById($id);
        return [
            'data' => [
                'id' => $row->id,
                'name' => $row->name,
                'phone' => $row->phone,
                'email' => $row->email,
                'avatar' => $row->avatar,
                'status' => $row->status,
                'roles' =>  $row->getRoleIds(),
            ],
        ];
    }

    /**
     * @throws ValidationException
     */
    public function store(): JsonResponse
    {
        $params = $this->validate(
            $this->request,
            [
                'name' => 'required|string',
                'phone' => 'required|string|regex:/^1[34578]\d{9}$/|unique:admins,phone',
                'email' => 'required|string|email|unique:admins,email',
                'password' => ['required', 'string', 'min:6', 'max:16', 'regex:/^(?=.*[A-Za-z])(?=.*\d).+$/'],
                'confirm_password' => 'required|string|same:password',
                'avatar' => 'required|string',
                'status' => 'required|integer',
            ],
            $this->validateMessages
        );
        $params['password'] = Hash::make($params['password']);
        unset($params['confirm_password']);
        $row = $this->repository->create($params);
        $roles = $this->request->input('roles', []);
        $row->syncRoles($roles);
        return $this->responseCreated();
    }

    /**
     * @throws ValidationException
     */
    public function update($id): JsonResponse
    {
        $params = $this->validate(
            $this->request,
            [
                'name' => 'required|string',
                'phone' => 'required|string|regex:/^1[34578]\d{9}$/|unique:admins,phone,' . $id . ',id',
                'email' => 'required|string|email|unique:admins,email,' . $id . ',id',
                'password' => ['nullable', 'string', 'min:6', 'max:16', 'regex:/^(?=.*[A-Za-z])(?=.*\d).+$/'],
                'confirm_password' => 'nullable|string|same:password',
                'avatar' => 'nullable|string',
                'status' => 'nullable|integer',
            ],
            $this->validateMessages
        );
        $row = $this->repository->getById($id);
        if (!empty($params['password'])) {
            $params['password'] = Hash::make($params['password']);
        }else{
            unset($params['password']);
        }
        unset($params['confirm_password']);
        $row->update($params);
        $roles = $this->request->input('roles', []);
        $row->syncRoles($roles);
        return $this->responseSuccess();
    }

    public function destroy($id): JsonResponse
    {
        $row = $this->repository->getById($id);
        $row->delete();
        $row->removeRoles();
        return $this->responseDeleted();
    }
}
